import { readdirSync, stat } from 'fs-extra';
import Client from 'ftp';
import * as path from 'path';
interface FtpOptions {
    host: string;
    user: string;
    password: string;
    secure?: boolean; // 如果使用 FTPS，则设置为 true
    port?: number; // 默认是 21，如果是 FTPS，则可能是 990 或其他
    encoding?: string;
}
export function uploadFileToFtp(localFilePath: string, remoteFilePath: string, options: FtpOptions): Promise<void> {
    return new Promise<void>((resolve, reject) => {
        const client = new Client();
        client.on(`ready`, () => {
            client.put(localFilePath, remoteFilePath, (err) => {
                if (err) return reject(err);
                client.end()
                resolve()
            })
        })
        client.connect(options);
    });
}
export async function ftpListDir(client: Client, root: string) {
    const list: any[] = await new Promise((resolve, reject) => {
        client.list(root, false, (err, items) => {
            if (err) {
                return reject(err);
            }
            resolve(items)
        })
    })
    return list.map((item: any) => {
        const name: string = item.name;
        item.name = Buffer.from(name.split('').map((i, j) => name.charCodeAt(j))).toString('utf8')
        return item;
    })
}
export function uploadDirToFtp(localPath: string, remotePath: string, options: FtpOptions): Promise<void> {
    return new Promise((resolve, reject) => {
        const client = new Client();
        client.on(`ready`, async () => {
            try {
                const srcFiles = readdirSync(localPath);
                await Promise.all(srcFiles.map(file => {
                    return new Promise<void>(async (resolve, reject) => {
                        const localFilePath = path.join(localPath, file)
                        const fileStat = await stat(localFilePath)
                        if (fileStat.isFile()) {
                            const remoteFilePath = [remotePath, file].join('/')
                            client.put(localFilePath, remoteFilePath, (err) => {
                                if (err) return reject(err);
                                resolve()
                            })
                        } else {
                            resolve()
                        }
                    })
                }))
                resolve()
            } catch (e) {
                reject(e)
            }
            finally {
                client.end()
            }
        })
        client.connect(options);
    });
}
